package cn.sxw.ld.module.user.service.impl;

import cn.sxw.ld.module.user.mapper.EmployeeMapper;
import cn.sxw.ld.module.user.service.EmployeeService;
import cn.sxw.ld.module.user.pojo.Employee;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

/**
 * ClassName:EmployeeServiceImpl
 * Package:cn.sjxy.service.impl
 * Description:
 *
 * @Date:2022/5/23 18:37
 * @Author:SXW
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Override
    public Page getPage(int page, int pageSize, String name, Boolean isAdmin) {
        // 分页构造器
        Page pageInfo = new Page(page, pageSize);
        // 条件构造器
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper();
        // 添加条件查询，先判断 name 是否为空，为空则不添加条件
        wrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        // 添加排序条件
        wrapper.orderByDesc(Employee::getUpdateTime);
        if (!isAdmin) {
            // 非管理员，添加查询条件，查询除了管理员外的所有数据
            wrapper.ne(Employee::getId, 1);
        }
        // 执行查询
        this.page(pageInfo, wrapper);
        return pageInfo;
    }

    @Override
    public boolean saveCheck(Employee employee) {
        // 判断是否需要密码初始化
        if (StringUtils.isNotEmpty(employee.getPassword())) {
            employee.setPassword(DigestUtils.md5DigestAsHex(employee.getPassword().getBytes()));
        } else {
            // 新增员工时，设置一个初始密码，使用 md5 加密
            employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        }
        // 判断是否存在同手机号账户
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getPhone, employee.getPhone());
        Employee one = this.getOne(wrapper);
        if (one == null) {
            this.save(employee);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean updateCheck(Employee employee) {
        // 修改过密码，更新插入时加密
        if (StringUtils.isNotEmpty(employee.getPassword())) {
            employee.setPassword(DigestUtils.md5DigestAsHex(employee.getPassword().getBytes()));
        } else {
            employee.setPassword(null);
        }
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getId, employee.getId());
        return this.update(employee, wrapper);
    }
}
